/*	BuildScienceFacility class definition.
 *
*/

#include "BuildingPlacer.h"
#include "BuildScienceFacility.h"

void BuildScienceFacility::Enter()
{
	DEBUG_PRINT("BuildScienceFacility(%p) %s entering\n", this, GetName().c_str());

}

void BuildScienceFacility::Execute()
{
	DEBUG_PRINT("BuildScienceFacility(%p) %s executing\n", this, GetName().c_str());
	if(!builder)
	{
		Base* base = BB->GetBases()->front();
		std::list<BWAPI::Unit*>* scvs = (base)->GetUnitsByType(BWAPI::UnitTypes::Terran_SCV);
		std::list<BWAPI::Unit*>::iterator it = scvs->begin();
			
		if (!builder)
		{
			for (; it!=scvs->end(); it++)
			{
				if (((*it)->isGatheringMinerals() || (*it)->isIdle()) && !(*it)->isCarryingMinerals()) break;
			}
			if(it == scvs->end())
			{
				control->FinishWithSuccess();
				return;
			}
			builder = (*it);
		}
		
		BWAPI::TilePosition pos = BuildPlacer->getBuildLocationNear(base->GetBaseLocation(),BWAPI::UnitTypes::Terran_Science_Facility);
		DEBUG_PRINT("BuildScienceFacility(%p) attempting to build barracks at tile position(%d,%d).\n", this, pos.x(),pos.y());
		builder->build(pos,BWAPI::UnitTypes::Terran_Science_Facility);
		BB->ResetOrder();
	}
	else if(builder)
	{
		if(!builder->exists())
		{
			builder = NULL;
			BB->Refund(BWAPI::UnitTypes::Terran_Science_Facility);
		}
		else if (builder->isConstructing()&& builder->getBuildUnit())
			builder = NULL;
		else if (builder->getLastCommand().getType() == BWAPI::UnitCommandTypes::Build && !builder->getBuildUnit())
		{

		}
		else
		{
			BB->Refund(BWAPI::UnitTypes::Terran_Science_Facility);
			builder = NULL;
		}
	}
	control->FinishWithSuccess();
}

void BuildScienceFacility::Exit()
{
	DEBUG_PRINT("BuildScienceFacility(%p) %s exiting\n", this, GetName().c_str());
	
}

bool BuildScienceFacility::CheckConditions()
{
	DEBUG_PRINT("BuildScienceFacility(%p) %s checking conditions\n", this, GetName().c_str());
	
	std::list<BWAPI::Unit*>* fac = BB->GetBuildingsByTypeGeneral(BWAPI::UnitTypes::Terran_Science_Facility);
	if(fac)
	{
		if(fac->size() < 1)
		{
			if(BB->isBuildBuilding(BWAPI::UnitTypes::Terran_Science_Facility) )
			{
				DEBUG_PRINT("BuildScienceFacility(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
				BB->SpendResources(BWAPI::UnitTypes::Terran_Science_Facility);
				return true;
			}
			else if (builder)
				return true;
		}
	}
	else
	{
		if(BB->isBuildBuilding(BWAPI::UnitTypes::Terran_Science_Facility) )
		{
			DEBUG_PRINT("BuildScienceFacility(%p) %s checked conditions and has %d minerals to spend\n", this, GetName().c_str(), BB->GetMineralsToSpend());
			BB->SpendResources(BWAPI::UnitTypes::Terran_Science_Facility);
			return true;
		}
		else if(builder)
			return true;

	}

	return false;
}